import urllib
import wsgiref.handlers

from google.appengine.ext import webapp
from google.appengine.api import users
from google.appengine.ext import db

from Img import Img

class deleteimg(webapp.RequestHandler):
    def get(self):
        user = users.get_current_user()

        if not user:
            self.redirect(users.create_login_url(urllib.unquote_plus(self.request.uri)))
            return
        #get the imgId
        imgId = self.request.path_qs[len('/delete/'):]
        #fetch img from db
        imgs = Img.all().filter('imgId = ', imgId).fetch(1)
        if len(imgs) > 0:
            #image exists
            img = imgs[0]
            if user.email() == img.uploader.email():
                #we delete it
                img.delete()
            self.redirect('/list/')
        else:
            #image does not exists, we show error
            self.redirect('/error/' + 'There is no image with id [' + imgId + ']')
            return
    
def main():
    application = webapp.WSGIApplication(
                           [('/delete/.*', deleteimg)],
                           debug=True)
    wsgiref.handlers.CGIHandler().run(application)

if __name__ == '__main__':
    main()

